<?php
// +----------------------------------------------------------------------
// | title: 标题注释
// +----------------------------------------------------------------------
// | Author: TZ.Leong
// +----------------------------------------------------------------------
// | Date: 2019/7/9 15:07
// +----------------------------------------------------------------------

namespace app\single\controller;


use cmf\controller\AdminBaseController;
use think\Db;
use think\exception\DbException;
use think\facade\Log;
use app\single\model\LogassetsModel;
use think\facade\Request;
use think\paginator\driver\Bootstrap;


class GameLogController extends AdminBaseController
{
    /*组装参数*/
    protected $dataInfo = array();
    protected $whereData = array();
    protected $page = null;

    /**
     * 日志展示
     */
    public function showLog()
    {
        $logType = $this->request->param('log_type', "", "trim");//日志分类
        $logIndex = $this->request->param('log_index', "", "trim");//日志分类子类型
        //日志配置目录
        $fileName = APP_PATH . APP_NAME . "/config/game_log/" . $logType . ".php";
        Log::write("file:" . $fileName . "文件不存在", "error");
        if (!file_exists($fileName)) {
            $this->error("file:" . $fileName . "文件不存在");
        }
        $logConfArr = include_once($fileName);

        //本日志配置
        $logConf = $logConfArr[$logIndex];
        //是否需要特殊日志处理方法
        if (is_array($logConf['table_name']) && $logConf['table_name']['function']) {
            //使用配置的function
            $getDataFunction = $logConf['table_name']['function'];
        } else {
            //默认为getData
            $getDataFunction = 'getData';
        }
        //可能要去掉一些路径带上去的东西
        $searchData = $this->request->param();
        if (isset($logConf["unset_field"])) {
            foreach ($logConf["unset_field"] as $field) {
                unset($searchData[$field]);
            }
        }
        //创建查询条件框
        $whereHtml = $this->buildSearchStr($logConf['where'] ?? [], $logConf["where_merge"] ?? []);
        //导出
        $export = input("export", 0);
        if ($export) {
            $this->exportData($getDataFunction, $logConf);
            exit();
        }
        //开始执行
        $this->$getDataFunction($logConf);
        //分页模版赋值
        $this->dataInfo->appends($searchData);
        $this->page = $this->dataInfo->render();
        //模板配置
        $this->assign(array(
            'logConf' => $logConfArr,
            'logType' => $logType,
            'logIndex' => $logIndex,
            'whereHtml' => $whereHtml,
            'headHtml' => $this->showHead($logConf['show']),
            'data' => $this->dataInfo,
            'page' => $this->page,
            "paramArr" => ["log_type" => $logType],
            "action" => $this->request->action(),
            "export" => $logConf["export"] ?? false
        ));
        return $this->fetch($logConf['display'] ?? "show_log");
    }

    /**
     * 默认获取数据方法
     * @param $logConf
     * @return array
     */
    private function getData($logConf)
    {
        $where = $this->getWhere($this->whereData);
        //配置了必须要查询条件并且查询条件为空，不做任何处理
        if (isset($logConf["need_where"]) && empty($where)) {
            return $this->dataInfo;
        }
        //如果没有dataInfo说明是自己组装
        $tableName = $logConf['table_name'];
        if (!empty($tableName)) {
            //最终要输出的数据
            $model = Db::table(config("database.log") . ".log_" . $tableName);
            //组装数据信息
            $this->dataInfo = $model->where($where)->order('time DESC,id desc')->paginate(self::$pageSize);
            echo $model->getLastSql();
        }
        return $this->dataInfo;
    }

    /**
     * 导出数据
     * @param $method
     * @param $logConf
     */
    private function exportData($method, $logConf)
    {
        self::$pageSize = 999999;
        $data = $this->$method($logConf);
        $exportData[] = $this->showHead($logConf["show"]);
        require_once APP_PATH . APP_NAME . "/logs_fun.php";
        foreach ($data as $i => $vo) {
            $i++;
            foreach ($logConf["show"] as $field => $v) {
                if (isset($v['function']) && is_callable($v['function'])) {
                    $params = $v['param'] ?? ['field' => $field];
                    $exportData[$i][$field] = call_user_func($v['function'], $vo, $params);
                } //默认值
                elseif (isset($v["default"])) {
                    $exportData[$i][$field] = $v["default"];
                } //记录值
                else {
                    $exportData[$i][$field] = $vo[$field];
                }
            }
        }
        exportExcel($exportData, $logConf["title"] . "_" . time());
    }

    /**
     * 登陆日志
     */
    public function loginData(): \think\Paginator
    {
        $where = $this->getWhere($this->whereData);
        $model = Db::table(config("database.log") . ".log_login");
        $this->dataInfo = $model->where($where)->alias("l")
            ->leftJoin([config("database.game") . ".role" => "p"], "p.id = l.role_id")
            ->field("l.*,p.name,p.lev")
            ->order("l.time DESC")->paginate(self::$pageSize);
        Log::write("last query sql:", $model->getLastSql());
        return $this->dataInfo;
    }


    protected function mailLogData(): \think\Paginator
    {
        $where = $this->getWhere($this->whereData);
        $newWhere = [];
        foreach ($where as $w) {
            $field = $w[0];
            if ($field == "id") {
                $w[0] = "l.to_rid";
            }
            if ($field == "name"){
                $w[0] = "l.to_name";
            }
            $newWhere[] = $w;
        }
        $model = Db::table(config("database.game") . ".log_mail");
        $this->dataInfo = $model->where($newWhere)->alias("l")
            ->leftJoin([config("database.game") . ".role" => "p"], "p.id = l.from_rid")
            ->field("l.*,p.name")
            ->order("l.send_time DESC")->paginate(self::$pageSize);
        Log::write("last query sql:", $model->getLastSql());
        return $this->dataInfo;
    }

    //道具日志
    public function itemData(): \think\Paginator
    {
        $where = $this->getWhere($this->whereData);
        // Log::write("debug where data" . json_encode($where, true) . __LINE__);
        // $whereType = 1;
        $whereType = 0;
        $newWhere = [];
        foreach ($where as $w) {
            $field = $w[0];
            if ($field == "s_type") {
                $whereType = $w[2];
                continue;
            }
            if ($field == "type" && $w[2] == -999) {
                continue;
            }
            
            $newWhere[] = $w;
        }

        // Log::write("debug newwhere type ".$newWhere );
        $table1 = config("database.log") . ".log_item";
        $table2 = config("database.log") . ".log_item_use";
        $table3 = config("database.game") . ".role";

        $whereSql = '';
        foreach ($newWhere as $condition) {
            if (is_array($condition)) {
                $field = $condition[0];
                $operator = $condition[1];
                $value = $condition[2];
                if ($operator == "between" || $operator == "BETWEEN") {
                    $whereSql .= " AND $field $operator $value[0] and $value[1]";
                } else {
                    if (is_array($value)) {
                        $value = implode(',', $value);
                        $whereSql .= " AND $field $operator ($value)";
                    } else {
                        $whereSql .= " AND $field $operator '$value'";
                    }
                }
            } else {
                $whereSql .= " AND $condition";
            }
        }


        // Log::write("debug where type ".json_encode($whereType));
        $sql = "";
        if ($whereType == 1) {
            $sql = "SELECT l.*, p.name,1 as s_type FROM $table1 l LEFT JOIN $table3 p ON p.id = l.role_id WHERE " . ltrim($whereSql, ' AND ') . " ORDER BY time DESC";
        } elseif ($whereType == 2) {
            $sql = "SELECT l.*, p.name,2 as s_type FROM $table2 l LEFT JOIN $table3 p ON p.id = l.role_id WHERE " . ltrim($whereSql, ' AND ') . " ORDER BY time DESC";
        } else {
            $sql = "(SELECT l.*, p.name,1 as s_type FROM $table1 l LEFT JOIN $table3 p ON p.id = l.role_id WHERE " . ltrim($whereSql, ' AND ') . ")
                    UNION
                    (SELECT l.*, p.name,2 as s_type FROM $table2 l LEFT JOIN $table3 p ON p.id = l.role_id WHERE " . ltrim($whereSql, ' AND ') . ")
                    ORDER BY time DESC";
        }


        Log::write("debug itemsql  ".$sql);

        $page = Request::instance()->param('page', 1);
        $countSql = "SELECT COUNT(*) as total FROM (($sql) AS temp)";
        $total = Db::query($countSql)[0]['total'];

        $pageSql = $sql . " LIMIT " . ($page - 1) * self::$pageSize . ", " . self::$pageSize;
        $list = Db::query($pageSql);

        $paginator = new Bootstrap($list, self::$pageSize, $page, $total, false, [
            'path' => Bootstrap::getCurrentPath(),
        ]);

        $this->dataInfo = $paginator;
        // Log::write("last query sql:", $model->getLastSql());
        return $this->dataInfo;
    }


    public function heroData(){
        $where = $this->getWhere($this->whereData);
        // Log::write("debug where data" . json_encode($where, true) . __LINE__);
        $whereType = 1;
        $newWhere = [];
        foreach ($where as $w) {
            $field = $w[0];
            if ($field == "operate") {
                // $whereType = $w[2];
                 $w[0] = "l.otp_type";
                 if ($w[2] ==2){
                    $w[2] =1;
                 }
                 if($w[2] ==1){
                    $w[2] =0;
                 }
                // continue;
            }
            if ($field == "type" && $w[2] == -999) {
                continue;
            }
            if ($field == 'type_str' &&$w[2] == 0){
               continue; 
            }
            $newWhere[] = $w;
        }

        $table = ".log_hero";
        // switch ((int) $whereType) {
        //     case 2:
        //         $table = ".log_item_use";
        //         break;
        //     case 1:
        //     default:
        //         $table = ".log_item";
        //         break;
        // }

        $model = Db::table(config("database.log") . $table);
        $this->dataInfo = $model->where($newWhere)->alias("l")
            ->leftJoin([config("database.game") . ".role" => "p"], "p.id = l.role_id")
            ->field("l.*,p.name")
            ->order("l.time DESC")->paginate(self::$pageSize);
        Log::write("last query sql:", $model->getLastSql());
        return $this->dataInfo;
    }


    public function heroDataStar(){
        $where = $this->getWhere($this->whereData);
        // Log::write("debug where data" . json_encode($where, true) . __LINE__);
        $whereType = 1;
        $newWhere = [];
        foreach ($where as $w) {
            $field = $w[0];
            if ($field == "operate") {
                // $whereType = $w[2];
                 $w[0] = "l.otp_type";
                 if ($w[2] ==2){
                    $w[2] =1;
                 }
                 if($w[2] ==1){
                    $w[2] =0;
                 }
                // continue;
            }
            if ($field == "type" && $w[2] == -999) {
                continue;
            }
            if ($field == 'type_str' &&$w[2] == 0){
               continue; 
            }
            $newWhere[] = $w;
        }

        $table = ".log_hero_star";
        // switch ((int) $whereType) {
        //     case 2:
        //         $table = ".log_item_use";
        //         break;
        //     case 1:
        //     default:
        //         $table = ".log_item";
        //         break;
        // }

        $model = Db::table(config("database.log") . $table);
        $this->dataInfo = $model->where($newWhere)->alias("l")
            ->leftJoin([config("database.game") . ".role" => "p"], "p.id = l.role_id")
            ->field("l.*,p.name")
            ->order("l.time DESC")->paginate(self::$pageSize);
        Log::write("last query sql:", $model->getLastSql());
        return $this->dataInfo;
    }



    public function coinData(): \think\Paginator
    {
        $where = $this->getWhere($this->whereData);
        // $table2 = config("database.game") . ".role";
        Log::write("debug where data" . json_encode($where, true) . __LINE__);
        // $whereType = 1;
        $whereType = 0;
        $newWhere = [];
        foreach ($where as $w) {
            $field = $w[0];
            if ($field == "op_type") {
                $whereType = $w[2];
                continue;
            }
            $newWhere[] = $w;
        }

        $table1 = config("database.game") . ".log_produce_coin";
        $table2 = config("database.game") . ".log_consume_coin";
        $table3 = config("database.game") . ".role";

        $whereSql = '';
        foreach ($newWhere as $condition) {
            if (is_array($condition)) {
                $field = $condition[0];
                $operator = $condition[1];
                $value = $condition[2];
                if ($operator == "between" || $operator == "BETWEEN") {
                    $whereSql .= " AND $field $operator $value[0] and $value[1]";
                } else {
                    if (is_array($value)) {
                        $value = implode(',', $value);
                        $whereSql .= " AND $field $operator ($value)";
                    } else {
                        $whereSql .= " AND $field $operator '$value'";
                    }
                }
            } else {
                $whereSql .= " AND $condition";
            }
        }

        $sql = "";
        if ($whereType == 1) {
            $sql = "SELECT l.role_id, p.name,l.role_lv, l.time,l.remain_coin, l.remain_bcoin,l.type_str, l.got_coin as coin, l.got_bcoin as bcoin, 1 as s_type FROM $table1 l LEFT JOIN $table3 p ON p.id = l.role_id WHERE " . ltrim($whereSql, ' AND ') . " ORDER BY time DESC";
        } elseif ($whereType == 2) {
            $sql = "SELECT l.role_id, p.name,l.role_lv, l.time,l.remain_coin, l.remain_bcoin,l.type_str, l.cost_coin as coin, l.cost_bcoin as bcoin, 2 as s_type FROM $table2 l LEFT JOIN $table3 p ON p.id = l.role_id WHERE " . ltrim($whereSql, ' AND ') . " ORDER BY time DESC";
        } else {
            $sql = "(SELECT l.role_id, p.name, l.role_lv, l.time,l.remain_coin ,l.remain_bcoin,l.type_str,l.got_coin as coin, l.got_bcoin as bcoin, 1 as s_type FROM $table1 l LEFT JOIN $table3 p ON p.id = l.role_id WHERE " . ltrim($whereSql, ' AND ') . ")
                    UNION
                    (SELECT l.role_id, p.name,l.role_lv, l.time,l.remain_coin, l.remain_bcoin,l.type_str, l.cost_coin as coin, l.cost_bcoin as bcoin, 2 as s_type FROM $table2 l LEFT JOIN $table3 p ON p.id = l.role_id WHERE " . ltrim($whereSql, ' AND ') . ")
                    ORDER BY time DESC";
        }

        // Log::write("last query sql:", $model->getLastSql());
        $page = Request::instance()->param('page', 1);
        $countSql = "SELECT COUNT(*) as total FROM (($sql) AS temp)";
        $total = Db::query($countSql)[0]['total'];

        $pageSql = $sql . " LIMIT " . ($page - 1) * self::$pageSize . ", " . self::$pageSize;
        $list = Db::query($pageSql);

        $paginator = new Bootstrap($list, self::$pageSize, $page, $total, false, [
            'path' => Bootstrap::getCurrentPath(),
        ]);

        $this->dataInfo = $paginator;
        // Log::write("last query sql:", $model->getLastSql());
        return $this->dataInfo;

    }


    public function goldData()
    {
        $where = $this->getWhere($this->whereData);
        // $table2 = config("database.game") . ".role";
        Log::write("debug where data" . json_encode($where, true) . __LINE__);
        // $whereType = 1;
        // $whereType = 1;
        $whereType =0;
        $newWhere = [];
        foreach ($where as $w) {
            $field = $w[0];
            if ($field == "op_type") {
                $whereType = $w[2];
                continue;
            }
            $newWhere[] = $w;
        }

        $table1 = config("database.game") . ".log_produce_gold";
        $table2 = config("database.game") . ".log_consume_gold";
        $table3 = config("database.game") . ".role";

        $whereSql = '';
        foreach ($newWhere as $condition) {
            if (is_array($condition)) {
                $field = $condition[0];
                $operator = $condition[1];
                $value = $condition[2];
                if ($operator == "between" || $operator == "BETWEEN") {
                    $whereSql .= " AND $field $operator $value[0] and $value[1]";
                } else {
                    if (is_array($value)) {
                        $value = implode(',', $value);
                        $whereSql .= " AND $field $operator ($value)";
                    } else {
                        $whereSql .= " AND $field $operator '$value'";
                    }
                }
            } else {
                $whereSql .= " AND $condition";
            }
        }
        if($whereType == -999){
            $whereType =0;
        }
        $sql = "";
        if ($whereType == 1) {
            $sql = "SELECT l.id, l.role_id,l.role_lv, l.time,l.remain_gold,l.type_str, l.remain_bgold, l.got_gold AS gold, l.got_bgold AS bgold,  p.name,  1 as s_type FROM $table1 l LEFT JOIN $table3 p ON p.id = l.role_id WHERE " . ltrim($whereSql, ' AND ') . " ORDER BY time DESC";
        } elseif ($whereType == 2) {
            $sql = "SELECT l.id, l.role_id,l.role_lv, l.time, l.remain_gold,l.type_str, l.remain_bgold, l.cost_gold AS gold, l.cost_bgold AS bgold,  p.name, 2 as s_type FROM $table2 l LEFT JOIN $table3 p ON p.id = l.role_id WHERE " . ltrim($whereSql, ' AND ') . " ORDER BY time DESC";
        } else {
            $sql = "(SELECT l.id, l.role_id, l.role_lv,l.time,l.remain_gold,l.type_str,l.remain_bgold,   l.got_gold AS gold, l.got_bgold AS bgold,  p.name, 1 as s_type FROM $table1 l LEFT JOIN $table3 p ON p.id = l.role_id WHERE " . ltrim($whereSql, ' AND ') . ")
                    UNION
                    (SELECT l.id, l.role_id,l.role_lv, l.time, l.remain_gold, l.type_str,l.remain_bgold, l.cost_gold AS gold, l.cost_bgold AS bgold,  p.name, 2 as s_type FROM $table2 l LEFT JOIN $table3 p ON p.id = l.role_id WHERE " . ltrim($whereSql, ' AND ') . ")
                    ORDER BY time DESC";
        }

        $page = Request::instance()->param('page', 1);
        $countSql = "SELECT COUNT(*) as total FROM (($sql) AS temp)";
        $total = Db::query($countSql)[0]['total'];

        $pageSql = $sql . " LIMIT " . ($page - 1) * self::$pageSize . ", " . self::$pageSize;
        $list = Db::query($pageSql);

        $paginator = new Bootstrap($list, self::$pageSize, $page, $total, false, [
            'path' => Bootstrap::getCurrentPath(),
        ]);

        $this->dataInfo = $paginator;
        Log::write("last query sql:", $sql);
        return $this->dataInfo;

    }




    //资产日志
    public function assetsData()
    {
        $where = $this->getWhere($this->whereData);

        $table1 = config("database.game") . ".log_assets";
        $table2 = config("database.game") . ".role";
        $sql = "select l.*,p.name,(cast(l.new_value as SIGNED)  -cast(l.old_value as SIGNED)) as update_value  from $table1 l  ";


        $newWhere = [];
        foreach ($where as $w) {
            $field = $w[0];
            $operator = $w[1];
            $value = $w[2];

            if ($field == 'op_type') {
                switch ((int) $value) {
                    case 2: //消耗
                        $newWhere[] = "(cast(l.new_value as SIGNED) - cast(l.old_value as SIGNED)) < 0";
                        break;
                    case 1: //获取
                        $newWhere[] = "(cast(l.new_value as SIGNED) - cast(l.old_value as SIGNED)) > 0";
                        break;
                    default:
                        break;
                }
                continue;
            }

            if ($field == 'type' && $value == 0) {
                continue;
            }

            if ($field == 'time') {
                $newWhere[] = ["l.time", $operator, $value];
            } elseif ($field == 'log_type') {
                if ($value != 0) {
                    $newWhere[] = ["l.type", $operator, $value];
                }

            } else {
                $newWhere[] = ["l." . $field, $operator, $value];
            }

        }



        $sql .= "left join $table2 p on l.role_id = p.id ";
        if (!empty($newWhere)) {
            $whereSql = '';
            foreach ($newWhere as $condition) {
                if (is_array($condition)) {
                    $field = $condition[0];
                    $operator = $condition[1];
                    $value = $condition[2];
                    if ($operator == "between" || $operator == "BETWEEN") {
                        $whereSql .= " AND $field $operator $value[0] and $value[1]";
                    } else {
                        if (is_array($value)) {
                            $value = implode(',', $value);
                            $whereSql .= " AND $field $operator ($value)";
                        } else {
                            $whereSql .= " AND $field $operator '$value'";
                        }
                    }

                } else {
                    $whereSql .= " AND $condition";
                }
            }
            $sql .= " WHERE " . ltrim($whereSql, ' AND ');
        }

        $sql .= "  order by `time` desc";

        $page = Request::instance()->param('page', 1);
        $w = " WHERE " . ltrim($whereSql, ' AND ');
        $countSql = "SELECT COUNT(1) AS total FROM {$table1} as l $w   ;";
        $total = Db::query($countSql)[0]['total'];
        $pageSql = $sql . " LIMIT " . ($page - 1) * self::$pageSize . ", " . self::$pageSize;
        Log::write("debug page sql " . $pageSql);
        // 3. 执行分页查询
        $list = Db::query($pageSql);
        // 4. 创建分页对象（支持模板渲染）
        $paginator = new Bootstrap($list, self::$pageSize, $page, $total, false, [
            'path' => Bootstrap::getCurrentPath(),
        ]);

        $this->dataInfo = $paginator;

        return $this->dataInfo;
    }

    /**
     * 生成搜索框
     * @param array $data 查询条件配置
     * @param array $mergeData 合并查询条件，如一些隐藏的
     * @return string
     */
    public function buildSearchStr($data = array(), $mergeData = array()): string
    {
        //创建查询字段
        $this->whereData = $data;
        if (empty($this->whereData)) {
            $this->whereData = array(
                'role_id' => array('name' => '玩家ID', 'type' => 'text', 'value' => ''),
                'nickname' => array('name' => '角色名', 'type' => 'text', 'value' => ''),
                'day' => array('name' => '时间', 'type' => 'date', 'keep_date' => true, 'values' => array('start_date' => date('Y-m-d'), 'end_date' => date('Y-m-d'))),
            );
        }
        //如果配置了默认以外多出来的，需要合并在一起
        if (!empty($mergeData)) {
            $this->whereData = array_merge($this->whereData, $mergeData);
        }
        //创建查询字符串
        $search = '';
        $nbsp = "&nbsp;&nbsp;";
        foreach ($this->whereData as $id => $val) {
            Log::write("debug id".$id." val" .json_encode($val));
            //下拉
            if ($val['type'] == 'select') {
                $class = $val["class"] ?? "";
                $search .= (isset($val['name']) ? $val["name"] . "：" : "") . "<select name='{$id}' id='{$id}' class='form-control " . $class . "'>";
                foreach ($val['values'] as $k => $v) {
                    if ($k == $this->request->param($id, $val["value"])) {
                        $search .= "<option selected='selected' value='{$k}'>{$v}</option>";
                    } else {
                        $search .= "<option value='{$k}'>{$v}</option>";
                    }
                }
                $search .= "</select>{$nbsp}";
            } //日期
            elseif ($val['type'] == 'date') {
                $search .= $val['name'] . "：";
                if (isset($val['values'])) {//时间期间
                    $startDate = $this->request->param('start_date', $val['values']['start_date']);
                    $endDate = $this->request->param('end_date', $val['values']['end_date']);
                    $search .= "<input type='text' class='form-control js-date' style='width: 105px;' name='start_date' id='start_date' value='{$startDate}'/>-";
                    $search .= "<input type='text' class='form-control js-date' style='width: 105px;' name='end_date' id='end_date' value='{$endDate}'/>{$nbsp}";
                } elseif (isset($val['value'])) {
                    $date = $this->request->param("date", $val["value"]["date"]);
                    $search .= "<input type='text' class='form-control js-date' style='width: 105px;' name='date' id='date' value='{$date}'/>{$nbsp}";
                }
            } elseif ($val['type'] == 'date_time') {
                $search .= $val['name'] . "：";
                if (isset($val['values'])) {//时间期间
                    $startDate = $this->request->param('start_date', $val['values']['start_date']);
                    $endDate = $this->request->param('end_date', $val['values']['end_date']);
                    $search .= "<input type='text' class='form-control js-datetime' style='width: 200px;' name='start_date' id='start_date' value='{$startDate}'/>-";
                    $search .= "<input type='text' class='form-control js-datetime' style='width: 200px;' name='end_date' id='end_date' value='{$endDate}'/>{$nbsp}";
                } elseif (isset($val['value'])) {
                    $date = $this->request->param("date", $val["value"]["date"]);
                    $search .= "<input type='text' class='form-control js-datetime' style='width: 200px;' name='date' id='date' value='{$date}'/>{$nbsp}";
                }
            }
            //区间
            elseif ($val['type'] == 'between') {
                $search .= $val['name'] . "：";
                $minName = $val['value_names'][0];
                $maxName = $val['value_names'][1];
                $min = $this->request->param($minName, $val['values']['min']);
                $max = $this->request->param($minName, $val['values']['max']);
                $search .= "<input type='text' class='form-control' style='width:60px;' name='{$minName}' id='{$minName}' value='{$min}'/>-";
                $search .= "<input type='text' class='form-control' style='width:60px;' name='{$maxName}' id='{$minName}' value='{$max}'/>{$nbsp}";
            } //隐藏的
            elseif ($val["type"] == "hidden") {
                $value = $this->request->param($id, $val["value"]);
                $search .= "<input type='hidden' name='{$id}' id='{$id}' value='" . $value . "'/>{$nbsp}";
            } //查询物品
            elseif ($val["type"] == "searchItem") {
                $search .= "{$val['name']}：<input type='text' class='form-control selector' style='width: 130px;' data-action='selectNode' data-url='" . url('/admin/Ajax/getItem') . "' name='{$id}' value='" . $this->request->param($id) . "' id='{$id}' placeholder='物品名称或者ID搜索'>{$nbsp}";
            } else {
                //普通input
                $search .= "{$val['name']}：<input type='text' class='form-control' style='width: 130px;' name='{$id}' id='{$id}' value='" . $this->request->param($id) . "'/>{$nbsp}";
            }
        }
        return $search;
    }

    /**
     * 组装查询条件
     * @param $logConf
     * @return array
     */
    private function getWhere($logConf): array
    {
        $where = [];
        //获取配置信息
        foreach ($logConf as $k => $v) {
            //是否设置别名
            $field = isset($v["alias"]) ? $v["alias"] . "." . $k : $k;
            //如果配置了条件类型为data,强制特殊组装sql查询
            if ($v['type'] == 'date') {
                if ($v['values']) {
                    $startDate = $this->request->param('start_date', $v['values']['start_date']);
                    $endDate = $this->request->param('end_date', $v['values']['end_date']);
                    if ($startDate && $endDate) {
                        if (isset($v["keep_date"])) {
                            $where[] = [$field, "between", [date("Ymd", strtotime($startDate)), date("Ymd", strtotime($endDate))]];
                        } else {
                            $where[] = [$field, "between", [strtotime($startDate . " 00:00:00"), strtotime($endDate . " 23:59:59")]];
                        }
                    }
                }
            } else if ($v['type'] == 'date_time') {
                if ($v['values']) {
                    $startDate = $this->request->param('start_date', $v['values']['start_date']);
                    $endDate = $this->request->param('end_date', $v['values']['end_date']);
                    if ($startDate && $endDate) {
                        if (isset($v["keep_date"])) {
                            $where[] = [$field, "between", [date("Ymd His", strtotime($startDate)), date("Ymd H-i-s", strtotime($endDate))]];
                        } else {
                            $where[] = [$field, "between", [strtotime($startDate), strtotime($endDate)]];
                        }
                    }
                }
            }
            //查询最大最小范围
            elseif ($v['type'] == 'between') {
                $minName = $v['value_names'][0];
                $maxName = $v['value_names'][1];
                $min = $this->request->param($minName, $v['values']['min']);
                $max = $this->request->param($maxName, $v['values']['max']);
                if ($min >= 0 && $max >= $min) {
                    $where[] = [$field, "between", [$min, $max]];
                }
            } //其他常见方式
            else {
                // Log::info("debug k,v " .var_export($k)."v===".var_export($v));
                if(!isset( $v['value'])){
                    continue;
                }
                $getValue = $this->request->param($k, $v['value'], "urldecode");
                if (isset($v["function"]) && !empty($getValue)) {
                    if (isset($v["fields"]) && is_array($v["fields"])) {
                        $map = "";
                        foreach ($v["fields"] as $field) {
                            $map = $map ? $map . " OR " . $field . " = " . $this->$v["function"]($getValue, $field) : $field . " = " . $this->$v["function"]($getValue, $field);
                        }
                        $where[] = $map;
                    } else {
                        $where[] = [$field, "=", $this->$v["function"]($getValue, $v["param"])];
                    }
                } //如果配置了条件类型为no,表示不参与sql查询
                else if ($getValue != '' && $v['type'] != 'no' && $getValue != -999) {
                    if ($v['type'] == 'like') {
                        $where[] = [$field, "like", "%{$getValue}%"];
                    } elseif ($v['type'] == 'hidden' && $v['in']) {
                        $where[] = [$field, "in", $getValue];
                    } else {
                        $where[] = [$field, "=", $getValue];
                    }
                }
            }
        }
        return $where;
    }

    /**
     * 生成头部标题html
     * @param array $data 日志配置的show
     * @return html|array
     */
    public function showHead(array $data)
    {
        $thArr = [];
        foreach ($data as $k => $v) {
            if (is_array($v))
                $thArr[] = "$v[0]";
            else
                $thArr[] = "$v";
        }
        return $thArr;
    }

    public function _empty()
    {
        return $this->showLog();
    }
}